package com.example.plus.file.translator.util;

import org.springframework.boot.configurationprocessor.json.JSONArray;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;


/**
 * @author zhouxl
 * @DATE 2020/12/4
 * @descriptoin
 */
public class TranslatorUtil {

    public static String translate(String langFrom, String langTo,
                                   String word) throws Exception {
        String url = "https://translate.googleapis.com/translate_a/single?" +
                "client=gtx&" +
                "sl=" + langFrom +
                "&tl=" + langTo +
                "&dt=t&q=" + URLEncoder.encode(word, "UTF-8");

//        String ip = "116.21.94.96";
        URL obj = new URL(url);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();
//        httpPost.addHeader("x-forwarded-for","116.21.94.96");
//        con.setRequestProperty("x-forwarded-for",ip);
//        con.setRequestProperty("User-Agent", "Mozilla/5.0");
//        con.setRequestProperty("X-Forwarded-For", ip);
//        con.setRequestProperty("HTTP_X_FORWARDED_FOR", ip);
//        con.setRequestProperty("HTTP_CLIENT_IP", ip);


        con.setInstanceFollowRedirects(false);
        BufferedReader in = new BufferedReader(
                new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while ((inputLine = in.readLine()) != null) {
            response.append(inputLine);
        }
        in.close();
        return parseResult(response.toString());
    }

    private static String parseResult(String inputJson) throws Exception {
        /*
         * inputJson for word 'hello' translated to language Hindi from English-
         * [[["नमस्ते","hello",,,1]],,"en"]
         * We have to get 'नमस्ते ' from this json.
         */
        JSONArray jsonArray = new JSONArray(inputJson);
        JSONArray jsonArray2 = (JSONArray) jsonArray.get(0);
//        JSONArray jsonArray3 = (JSONArray) jsonArray2.get(0);
        String result = "";
        for (int i = 0; i < jsonArray2.length(); i++) {
            result += ((JSONArray) jsonArray2.get(i)).get(0).toString();
        }
        return result;
    }

}
